package com.itzg.filestats;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.prefs.Preferences;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DirTreeStatsMain {
	private static final Logger logger = LoggerFactory.getLogger(DirTreeStatsMain.class);


	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Analyzer analyzer = null;
		boolean guiMode = false;
		if (args.length >= 1) {
			analyzer = new Analyzer(new File(args[0]));
		}
		else {
			Preferences prefs = Preferences.userNodeForPackage(DirTreeStatsMain.class);
			JFileChooser fileChooser = new JFileChooser();
			String prevRootDir = prefs.get("rootDir", null);
			if (prevRootDir != null) {
				fileChooser.setSelectedFile(new File(prevRootDir));
			}
			fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			int result = fileChooser.showOpenDialog(null);
			if (result == JFileChooser.APPROVE_OPTION) {
				File selectedFile = fileChooser.getSelectedFile();
				analyzer = new Analyzer(selectedFile);
				prefs.put("rootDir", selectedFile.getAbsolutePath());
				guiMode = true;
			}
		}
		
		if (analyzer != null) {
			Thread analyzerThread = new Thread(analyzer);
			analyzerThread.start();
			try {
				analyzerThread.join();
				if (!guiMode) {
					System.out.println(analyzer);
				}
				else {
					JFrame frame = new ResultsFrame(analyzer);
					frame.setTitle(analyzer.getStartingDirectory().getAbsolutePath());
					frame.pack();
					frame.setVisible(true);
					frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				}
			} catch (InterruptedException e) {
				logger.error("Interrupted");
				return;
			}
		}
	}

}
